package device

import (
	"gitee.com/sansaniot/ssiot-gw-lib/ssiot/msgbus"
	"github.com/rs/zerolog/log"
)

var (
	configSetHandler ConfigSetFunc
	sensorSetFunc    SensorSetFunc
)

type (
	ConfigSetFunc func(uint64, string, interface{}) error
	SensorSetFunc func(uint64, string, interface{}) error
)

func RegisterConfigSetHandler(handler ConfigSetFunc) {
	configSetHandler = handler
}

func RegisterSensorSetHandler(handler SensorSetFunc) {
	sensorSetFunc = handler
}

func Login(devSn string, data interface{}) {
	iot := msgbus.NewMsgIoT(msgbus.LOGIN, "$", devSn, data)
	iot.Publish()
}

func Logout(devSn string) {
	iot := msgbus.NewMsgIoT(msgbus.LOGOUT, "$", devSn, nil)
	iot.Publish()
}

func ConfigSet(sid uint64, devSn string, config interface{}) {
	if configSetHandler == nil {
		log.Warn().Msgf("no config set func")
		return
	}

	err := configSetHandler(sid, devSn, config)
	if err == nil {
		AckConfigSet(sid, devSn, 200, "")
	} else {
		AckConfigSet(sid, devSn, 400, err.Error())
	}
}

func SensorSet(sid uint64, devSn string, setData interface{}) {
	if sensorSetFunc == nil {
		log.Warn().Msgf("no sensor set func")
		return
	}

	err := sensorSetFunc(sid, devSn, setData)
	if err == nil {
		AckSensorSet(sid, devSn, 200, "")
	} else {
		AckSensorSet(sid, devSn, 400, err.Error())
	}
}

func AckSensorSet(sid uint64, devSn string, code int, msg string) {
	iot := msgbus.NewMsgIoT(msgbus.ACK_SENSOR_SET, "$", devSn, nil)
	iot.Sid = sid
	iot.Code = code
	iot.Msg = msg
	iot.Publish()
}

func AckConfigSet(sid uint64, devSn string, code int, msg string) {
	iot := msgbus.NewMsgIoT(msgbus.ACK_CONFIG_SET, "$", devSn, nil)
	iot.Sid = sid
	iot.Code = code
	iot.Msg = msg
	iot.Publish()
}

func SensorPost(devSn string, data interface{}) {
	iot := msgbus.NewMsgIoT(msgbus.SENSOR_POST, "$", devSn, data)
	iot.Publish()
}
